package autohome.wz.job;

import autohome.wz.lib.AutoHomeNewsHelper;
import autohome.wz.lib.Common;
import autohome.wz.lib.HttpRequest;
import autohome.wz.model.AutoClub.TopicDetail;
import autohome.wz.model.AutoClub.TopicListItem;
import autohome.wz.model.AutoClub.TopicListResult;
import autohome.wz.model.AutoHomeNews;
import autohome.wz.model.BaseApiResult;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ${汽车之家论坛数据抓取}
 * Created with Administrator
 *
 * @author yanwei.yang on 2018-09-21 9:31
 **/
public class AutoClubJob implements Job {


    private static int currentPage = 1;

    private static int totalPage = 0;

    private static Logger logger = Logger.getLogger(AutoClubJob.class);


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        init();
    }


    public static void main(String[] args) {
        init();
    }

    private static void init() {
        Map<Integer, String> map = new HashMap<>(50);
        map.put(292, "美人生活秀");
        map.put(106, "现身说法");
        map.put(290, "一起看世界");
        map.put(104, "媳妇当车模");
        map.put(172, "论坛红人馆");
        map.put(368, "不一young");
        map.put(230, "论坛达人");
        map.put(358, "边走编说");
        map.put(436, "论坛播报");
        map.put(272, "大咖俱乐部");
        map.put(275, "小资情调");
        map.put(276, "家用好车");
        map.put(277, "SUV家族");
        map.put(278, "性能机器");
        map.put(295, "我是女车主");
        map.put(293, "环保先锋");
        map.put(279, "大旅行家");
        map.put(280, "车主有话说");
        map.put(168, "超级试驾员");
        map.put(326, "情怀老车");
        map.put(107, "原创大片");
        map.put(122, "改装有理");
        map.put(296, "时光映像");
        map.put(328, "短篇也精彩");
        map.put(282, "爱情连连看");
        map.put(290, "一起看世界");
        map.put(225, "港澳台游记");
        map.put(281, "骑行天下");
        map.put(287, "云贵之巅");
        map.put(289, "海天盛宴");

        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            Integer key = entry.getKey();
            String name = entry.getValue();
            currentPage = 1;
            totalPage = 0;
            LoadSection(key, name, currentPage);

        }

    }


    private static void LoadSection(int classId, String sectionName, int currentPage) {

        String url = "http://clubapi.in.autohome.com.cn/api/topic/getpushtopicbyidspaging?_appid=wz&classids=%s&pageindex=%s&pagesize=20";
        url = String.format(url, classId, currentPage);
        String apiResultContent = HttpRequest.sendGet(url, "");
        if (!apiResultContent.equals("")) {
            Gson gson = new Gson();
            BaseApiResult<TopicListResult> apiResult;
            try {
                apiResult = gson.fromJson(apiResultContent, new TypeToken<BaseApiResult<TopicListResult>>() {
                }.getType());
                if (apiResult != null) {
                    totalPage = apiResult.getResult().getPagecount();
                    TopicListResult topicListResult = apiResult.getResult();
                    if (topicListResult != null && topicListResult.getList().size() > 0) {

                        List<TopicListItem> list = topicListResult.getList();
                        for (TopicListItem topic : list
                        ) {
                            long topicId = topic.getTopicid();
                            //帖子标题
                            String title = topic.getLongtitle();
                            //String picUrl = Common.GetClubThumbnail(topic.getOriginalpic(), "12090");//帖子缩略图 120 90
                            String picUrl = topic.getOriginalpic();
                            //车系id
                            long bbsId = topic.getBbsid();
                            if (topicId > 0) {
                                TopicDetail detail = GetTopicDetail(topicId);
                                if (detail != null) {
                                    String content = detail.getContent();
                                    String postUserName = detail.getPost_membername();
                                    String postDate = detail.getPostdate();
                                    int days = Common.differenceDay(postDate);
                                    if (days <= 180) {
                                        String ttTag = detail.getTtag();
                                        AutoHomeNews model = new AutoHomeNews();
                                        model.setBiz_id(topicId);
                                        model.setCms_series_id(String.valueOf(bbsId));
                                        model.setImg_url(picUrl);
                                        model.setTitle(title);
                                        model.setContent(content);
                                        model.setIndex_detail("");
                                        model.setCms_tags(ttTag);
                                        model.setAuthor(postUserName);
                                        model.setPublish_time(Common.GetSqlTimeSpan(postDate));
                                        int bizType = 3;
                                        model.setBiz_type(bizType);
                                        //分类名称
                                        model.setCms_content_class(sectionName);
                                        int addResult = AutoHomeNewsHelper.Add(model);
                                        if (addResult > 0) {
                                            Common.showMessage(title + "入库成功");
                                        }
                                    }

                                }
                            }

                        }

                        currentPage++;
                        if (currentPage < totalPage) {
                            Common.showMessage("开始读取第" + currentPage + "页");
                            LoadSection(classId, sectionName, currentPage);
                        }
                    }
                }

            } catch (Exception e) {
                logger.error("AutoClubJob:" + e.getMessage());
            }
        }
    }

    /**
     * 获取帖子详情
     *
     * @param topicId 帖子Id
     * @return 新地址
     */
    private static TopicDetail GetTopicDetail(long topicId) {

        TopicDetail detail = new TopicDetail();
        if (topicId > 0) {
            String url = "http://clubapi.in.autohome.com.cn/api/topic/GetTopicById?topicid=%s&fields=bbs,bbsid,bbsname,topicid,title,content,ttag,post_membername,lastreplydate,postdate,replycount,viewcount&_appid=wz";
            url = String.format(url, topicId);
            String apiResultContent = HttpRequest.sendGet(url, "");
            if (!apiResultContent.equals("")) {

                try {
                    Gson gson = new Gson();
                    BaseApiResult<TopicDetail> topicDetailResult = gson.fromJson(apiResultContent, new TypeToken<BaseApiResult<TopicDetail>>() {
                    }.getType());
                    if (topicDetailResult != null && topicDetailResult.getReturncode() == 0) {
                        detail = topicDetailResult.getResult();
                    }

                } catch (Exception e) {
                    logger.error("GetTopicDetail:" + e.getMessage());
                }
            }
        }
        return detail;
    }


}
